<?php


namespace app\superadmin\controller;


use think\Db;
use think\facade\Request;

class Event extends LoggingBase
{

    private function GetConfig($Type)
    {
        if (!$Type) {
            mb_OutMessage(ErrCode_Toast, '参数有误！');
        }
        $Config = null;
        switch ($Type) {
            case 'User':
                $Config['Table'] = 'user';
                break;
            case 'Company':
                $Config['Table'] = 'company';
                break;
            default:
                break;
        }
        return $Config;
    }

    public function Add()
    {
        $Type = Request::has('Type') ? addslashes(Request::param('Type')) : '';
        $Data = Request::has('ID') ? Request::param('ID') : '';
        if (!$Data) {
            mb_OutMessage(ErrCode_Toast, '参数有误！');
        }
        $Data = json_decode($Data, true);
        $Config = $this->GetConfig($Type);
        if (!$Config) {
            mb_OutMessage(ErrCode_Toast, '配置有误！');
        }
        Db::startTrans();
        try {
            Db::table($Config['Table'])->insert($Data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal,'添加成功');
    }

    public function Edit()
    {
        $Type = Request::has('Type') ? addslashes(Request::param('Type')) : '';
        $ID = Request::has('ID') ? intval(Request::param('ID')) : 0;
        $Data = Request::has('ID') ? Request::param('ID') : '';
        if (!$ID) {
            mb_OutMessage(ErrCode_Toast, '参数有误！');
        }
        if (!$Data) {
            mb_OutMessage(ErrCode_Toast, '参数有误！');
        }
        $Data = json_decode($Data, true);
        $Config = $this->GetConfig($Type);
        if (!$Config) {
            mb_OutMessage(ErrCode_Toast, '配置有误！');
        }
        Db::startTrans();
        try {
            Db::table($Config['Table'])->where('ID',$ID)->update($Data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal,'添加成功');
    }

    /**
     * 刪除
     */
    public function Delete()
    {
        $Type = Request::has('Type') ? addslashes(Request::param('Type')) : '';
        $ID = Request::has('ID') ? intval(Request::param('ID')) : 0;

        if (!$ID) {
            mb_OutMessage(ErrCode_Toast, '参数有误！');
        }
        $Config = $this->GetConfig($Type);
        if (!$Config) {
            mb_OutMessage(ErrCode_Toast, '配置有误！');
        }
        Db::startTrans();
        try {
            Db::table($Config['Table'])->where('ID', $ID)->update(['IsDeleted', 1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal, '删除成功');
    }
}